<template>
  <div class="app-container">
    <div id="bar">
      <!--搜索、筛选-->
      <el-form
        :inline="true"
        class="demo-form-inline"
      >
        <el-form-item>
          <el-input
            v-model="filter_query.search"
            placeholder="搜索"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="filter_query.project"
            placeholder="项目"
          >
            <el-option
              v-for="item in projects"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="search"
          >
            查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="add_collection"
          >
            添加
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div id="table">
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        element-loading-text="玩命加载中..."
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          prop="name"
          label="接口名称"
        />
        <el-table-column
          prop="uri"
          label="接口路径"
        />
        <el-table-column
          prop="project_name"
          label="归属项目"
          show-overflow-tooltip
        />
        <el-table-column
          prop="user"
          label="创建用户"
          show-overflow-tooltip
        />
        <el-table-column
          prop="update_time"
          label="修改时间"
          show-overflow-tooltip
        />
        <el-table-column
          prop="create_time"
          label="创建时间"
          show-overflow-tooltip
        />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handle_edit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handle_delete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div id="edit">
      <el-dialog
        v-loading="loading"
        :title="dialog_title"
        :visible.sync="dialogFormVisible"
        element-loading-text="玩命加载中..."
      >
        <el-form :model="form">
          <el-tabs v-model="activeName">
            <el-tab-pane
              label="接口信息"
              name="first"
            >
              <el-form-item
                label="接口名称"
                :label-width="formLabelWidth"
              >
                <el-input
                  v-model="form.name"
                  style="width: 80%"
                />
              </el-form-item>
              <el-form-item
                label="接口路径"
                :label-width="formLabelWidth"
              >
                <el-input
                  v-model="form.uri"
                  style="width: 80%"
                />
              </el-form-item>
              <el-form-item
                label="归属项目"
                :label-width="formLabelWidth"
              >
                <el-select
                  v-model="form.project"
                  style="width: 80%"
                >
                  <el-option
                    v-for="item in projects"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane
              label="默认参数"
              name="second"
            >
              <el-form
                :inline="true"
                class="demo-form-inline"
              >
                <el-form-item
                  v-for="(domain, index) in paramsForm"
                  :key="domain.key"
                  style="width: 100%"
                >
                  <el-input
                    v-model="domain.name"
                    style="width: 30%"
                  />
                  <el-input
                    v-model="domain.value"
                    style="width: 30%"
                  />
                  <el-button @click.prevent="removeParams(domain)">
                    删除
                  </el-button>
                  <el-button @click="addParams">
                    添加
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane
              label="默认header"
              name="third"
            >
              <el-form
                :inline="true"
                class="demo-form-inline"
              >
                <el-form-item
                  v-for="(domain, index) in headersForm"
                  :key="domain.key"
                  style="width: 100%"
                >
                  <el-input
                    v-model="domain.name"
                    style="width: 30%"
                  />
                  <el-input
                    v-model="domain.value"
                    style="width: 30%"
                  />
                  <el-button @click.prevent="removeHeaders(domain)">
                    删除
                  </el-button>
                  <el-button @click="addHeaders">
                    添加
                  </el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-form>
        <div
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="dialogFormVisible = false">
            取 消
          </el-button>
          <el-button
            type="primary"
            :loading="button_loading"
            @click="operate"
          >
            确 定
          </el-button>
        </div>
      </el-dialog>
    </div>
    <div id="pagination">
      <el-pagination
        :current-page="currentPage"
        :page-size="filter_query.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { getProject } from '@/api/project'
import { getInterface, postInterface, putInterface, deleteInterface } from '@/api/interface'
export default {
  name: 'Interface',
  data: function() {
    return {
      currentPage: 1,
      total: 0,
      filter_query: {
        project: undefined,
        search: undefined,
        limit: 10,
        page: 1
      },
      projects: [],
      tableData: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      collectionFormVisible: false,
      showResultVisible: false,
      showResultInnerVisible: false,
      multipleSelection: null,
      dialog_title: '添加',
      form: {
        name: '',
        project: '',
        uri: '',
        params: '',
        headers: '',
        user: this.$store.getters.user
      },
      paramsForm: [{
        value: '',
        name: ''
      }],
      headersForm: [{
        value: '',
        name: ''
      }],
      formLabelWidth: '120px',
      case_data: [],
      value: [],
      loading: false,
      button_loading: false,
      id: undefined,
      report_data: '',
      report_detail_query: '',
      report_detail_data: [],
      activeName: 'first'
    }
  },
  mounted: function() {
    this.get_project_data()
    this.get_page_data()
  },
  methods: {
    addParams() {
      this.paramsForm.push({
        value: '',
        name: '',
        key: Date.now()
      })
    },
    removeParams(item) {
      var index = this.paramsForm.indexOf(item)
      if (this.paramsForm.length === 1) {
        this.$message.error('这是最后一个了,不可以在删除了！')
        return
      }
      if (index !== -1) {
        this.paramsForm.splice(index, 1)
      }
    },
    addHeaders() {
      this.headersForm.push({
        value: '',
        name: '',
        key: Date.now()
      })
    },
    removeHeaders(item) {
      var index = this.headersForm.indexOf(item)
      if (index !== -1) {
        this.headersForm.splice(index, 1)
      }
    },
    handleSizeChange(val) {
      this.filter_query.limit = val
      this.filter_query.page = 1
      this.get_page_data()
    },
    handleCurrentChange(val) {
      this.filter_query.page = val
      this.get_page_data()
    },
    data_to_string(data) {
      const tmp = new FormData()
      for (var key in data) {
        tmp.append(key, data[key])
      }
      return tmp
    },
    get_project_data: function() {
      getProject().then((response) => {
        this.projects = response.data.data
        console.log(this.projects)
      })
    },
    get_page_data: function() {
      this.loading = true //
      getInterface(this.filter_query).then((response) => {
        this.tableData = response.data.data
        this.total = response.data.count
        this.loading = false //
      })
    },
    search: function() {
      this.filter_query.page = 1
      this.get_page_data()
    },
    handleSelectionChange(val) {
      var ids = []
      for (var num in val) {
        ids.push(val[num].id)
      }
      this.multipleSelection = ids
    },
    handle_edit(row) {
      this.reset_params_headers(row)
      this.form = Object.assign({}, {
        name: row.name,
        project: row.project,
        uri: row.uri,
        id: row.id,
        user: this.$store.getters.user
      }) // 深拷贝
      this.dialog_title = '编辑'
      this.dialogFormVisible = true // 打开模态框
    },
    handle_delete(row) {
      this.$confirm('确认删除当前接口吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteInterface({ id: row.id }).then((response) => {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.get_page_data()
        }).catch((error) => {
          this.$message({
            type: 'error',
            message: error
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除'
        })
      })
    },
    add_collection() {
      this.reset_form()
      this.dialog_title = '添加'
      this.dialogFormVisible = true
    },
    reset_form() {
      // form数据置为空
      this.form = {
        name: '',
        project: '',
        uri: '',
        params: '',
        headers: '',
        user: this.$store.getters.user
      }
      this.paramsForm = [{
        value: '',
        name: ''
      }]
      this.headersForm =
                    [{
                      value: '',
                      name: ''
                    }]
    },
    set_params_headers() {
      const params = {}
      for (var num in this.paramsForm) {
        const item = this.paramsForm[num]
        if (item.name.length > 0) {
          params[item.name] = item.value
        }
      }
      this.form.params = JSON.stringify(params)

      const headers = {}
      for (var num in this.headersForm) {
        const item = this.headersForm[num]
        if (item.name.length > 0) {
          headers[item.name] = item.value
        }
      }
      this.form.headers = JSON.stringify(headers)
    },
    reset_params_headers(data) {
      const params = JSON.parse(data.params)
      const headers = JSON.parse(data.headers)
      this.paramsForm = []
      for (var key in params) {
        this.paramsForm.push({ name: key, value: params[key] })
      }
      this.headersForm = []
      for (var key in headers) {
        this.headersForm.push({ name: key, value: headers[key] })
      }
      // 当没有header和参数时需要默认显示一个kv对
      if (this.headersForm.length === 0) {
        this.headersForm = [{
          value: '',
          name: ''
        }]
      }
      if (this.paramsForm.length === 0) {
        this.paramsForm = [{
          value: '',
          name: ''
        }]
      }
    },
    operate() {
      this.button_loading = true
      this.set_params_headers()
      if (this.dialog_title === '添加') {
        postInterface(this.data_to_string(this.form)).then((response) => {
          this.button_loading = false
          if (response.data.code === 0) {
            this.dialogFormVisible = false // 关闭模态框
            this.get_page_data()
          } else {
            this.$message({
              type: 'error',
              message: response.data.msg
            })
          }
        }).catch((error) => {
          this.button_loading = false
          this.$message({
            type: 'error',
            message: error
          })
        })
      } else if (this.dialog_title === '编辑') {
        putInterface(this.data_to_string(this.form)).then((response) => {
          this.button_loading = false
          if (response.data.code === 0) {
            this.dialogFormVisible = false // 关闭模态框
            this.get_page_data()
          } else {
            this.$message({
              type: 'error',
              message: response.data.msg
            })
          }
        }).catch((error) => {
          this.button_loading = false
          this.$message({
            type: 'error',
            message: error
          })
        })
      }
    }
  }

}
</script>

<style scoped>
.line{
  text-align: center;
}
</style>

